local zaiqi = fk.CreateSkill{
    name = "hs__zaiqi",
}

local H = require "packages.ol_hegemony.util"

zaiqi:addEffect(fk.EventPhaseEnd,{
    can_trigger = function(self, event, target, player, data)
      if target == player and player:hasSkill(zaiqi.name) and player.phase == Player.Discard then
      local ids = {}
      local room = player.room
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(ids, info.cardId)
            end
          end
        end
      end, Player.HistoryTurn)
      local x = #table.filter(ids, function (id)
        return Fk:getCardById(id).color == Card.Red
      end)
      if x > 0 then
        event:setCostData(self, {extra_data = x})
        return true
         end
       end
     end,
      on_cost = function(self, event, target, player, data)
        local room = player.room
        local x =  event:getCostData(self).extra_data
        local targets = table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end)
        local tos = room:askToChoosePlayers(player,{
            targets = targets,
            min_num = 1,
            max_num = x,
            skill_name = zaiqi.name,
            prompt = "#heg__exzaiqi-ask:::"..x,
            cancelable = true
        })
        if #tos > 0 then
          room:sortByAction(tos)
          event:setCostData(self, {tos = tos} )
          return true
        end
      end,
      on_use = function(self, event, target, player, data)
        local room = player.room
        local targets = event:getCostData(self).tos
        for _, p in ipairs(targets) do
          if not p.dead then
            local choices = {"heg__exzaiqi_draw"}
            if player and not player.dead and player:isWounded() then
              table.insert(choices, "heg__exzaiqi_recover:"..player.id)
            end
            local choice = room:askToChoice(p,{
                choices = choices,
                skill_name = zaiqi.name,
                prompt = "#heg__exzaiqi-choice:"..player.id,
            })
            if choice == "heg__exzaiqi_draw" then
              p:drawCards(1, zaiqi.name)
            else
              room:recover({
                who = player,
                num = 1,
                recoverBy = p,
                skillName = zaiqi.name
              })
            end
          end
        end
      end,
})

Fk:loadTranslationTable{
    ["hs__zaiqi"] = "再起",
    [":hs__zaiqi"] = "弃牌阶段结束时，你可选择至多X名与你势力相同的角色（X为弃牌堆里于此回合内移至此区域的红色牌数），这些角色各选择：1.令你回复1点体力；2.摸一张牌。",

    ["#heg__exzaiqi-ask"] = "再起：选择至多%arg名与你势力相同的角色，这些角色各选择令你回复1点体力或摸一张牌",
    ["#heg__exzaiqi-choice"] = "再起：选择摸一张牌或令%src回复1点体力",
    ["heg__exzaiqi_draw"] = "摸一张牌",
    ["heg__exzaiqi_recover"] = "令%src回复1点体力",

    ["$hs__zaiqi1"] = "丞相助我！",
    ["$hs__zaiqi2"] = "起！",
}

return zaiqi